<template>
  <div class="roles">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 表单区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开页 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom','vcenter', i1 === 0 ? 'bdtop':'']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级菜单渲染 -->
              <el-col :span="6">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二三级菜单渲染 -->
              <el-col :span="18">
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '':'bdtop','vcenter']"
                >
                  <!-- 二级菜单 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级菜单 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <!-- 列表页 -->
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="rolesAllot(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限弹窗 -->
    <el-dialog title="分配权限" :visible.sync="rolesDialogVisible" width="50%" @close="resetRolesList">
      <el-tree
        :data="treeList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defultKey"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      // 控制分配权限弹窗显示隐藏
      rolesDialogVisible: false,
      treeList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      //  默认选中的id数组
      defultKey: [],
      // 选中要修改权限的角色ID
      roleID: 1
    }
  },
  mounted () {
    this.getRolesList()
  },
  methods: {
    // 获取所有权限列表信息
    async getRolesList () {
      const { data: res } = await this.$http.get('roles/')

      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败')
      }

      this.rolesList = res.data
    },
    // 根据id移除对应的权限
    async removeRightById (role, rightId) {
      const confirmRes = await this.$confirm(
        '此操作将永久移除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消移除权限')
      }

      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )

      if (res.meta.status !== 200) {
        return this.$$message.error('移除权限失败')
      }

      role.children = res.data
      this.$message.success(res.meta.msg)
    },
    // 分配权限按钮
    async rolesAllot (role) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      // 把角色id存起来
      this.roleID = role.id

      //   console.log(res)
      //   把数据存到本地data中
      this.treeList = res.data

      //   调用递归函数进行标记已有权限
      this.getLeafKeys(role, this.defultKey)

      this.rolesDialogVisible = true
    },
    // 利用递归函数重复获取三级权限下的所有id，并且存到defaultKey中
    getLeafKeys (node, arr) {
      // 如果node没有children则是三级的节点，这个时候把所有的id都push进arr中
      if (!node.children) return arr.push(node.id)

      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 关闭分配权限窗口的时候重置内容
    resetRolesList () {
      this.defultKey = []
    },
    // 点击为角色分配权限并保存到服务器
    async allotRights () {
      const keysIDArr = [
        // 获取选中的项目的id
        ...this.$refs.treeRef.getCheckedKeys(),
        // 获取半选中的项目的id
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 把拼接好的数组转成符合传输的字符串
      const idStr = keysIDArr.join(',')

      const { data: res } = await this.$http.post(
        `roles/${this.roleID}/rights`,
        {
          rids: idStr
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.errpr('分配权限失败')
      }

      this.rolesDialogVisible = false
      this.$message.success('更新权限成功')
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
